package ru.niir.goodfil.excel;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import ru.niir.goodfil.audit.util.Assert;
import ru.niir.goodfil.excel.client.ColumnModel;
import ru.niir.goodfil.excel.client.SheetModel;
import ru.niir.goodfil.excel.client.WorkbookModel;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class ExcelExport {
    public static void generate(List collection, WorkbookModel model, String target) throws IOException {
        Workbook wb = new HSSFWorkbook();

        Assert.notNull(wb);

        for (SheetModel sheetModel : model.getSheets()) {
            Sheet sheet = wb.createSheet(sheetModel.getTitle());

            ColumnModel[] columns = sheetModel.getColumns();

            Row header = sheet.createRow(0);

            for (int i = 0; i < columns.length; i++) {
                ColumnModel column = columns[i];
                Cell cell = header.createCell(i);
                cell.setCellValue(column.getHeaderModel().getTitle());

                if (column.getWidth() != null) {
                    sheet.setColumnWidth(i, column.getWidth());
                }
            }

            for (int i = 0; i < collection.size(); i++) {
                Row row = sheet.createRow(i + 1);
                Object o = collection.get(i);

                for (int j = 0; j < columns.length; j++) {
                    ColumnModel column = columns[j];
                    Cell cell = row.createCell(j);

                    cell.getCellStyle().setWrapText(true);

                    Object value = column.getValueExtractor().extract(o);
                    column.getRenderer().render(cell, value, column);
                }
            }
        }

        FileOutputStream fos = new FileOutputStream(target);
        wb.write(fos);
        fos.flush();
        fos.close();
    }
}
